import { Body, Controller, Get, Post, Query } from '@nestjs/common';
import { ShowBetService } from 'src/show-bet/show-bet.service';
import { PlanService } from 'src/plan/plan.service';
import { showBet, Wire } from 'generated/prisma';
import { WireService } from 'src/wire/wire.service';
import { PrismaService } from 'src/prisma/prisma.service';

@Controller('calculate-line')
export class CalculateLineController {
  constructor(
    private readonly planService: PlanService,
    private readonly showBetService: ShowBetService,
    private readonly wireService: WireService,
    private readonly prisma: PrismaService,
  ) {}

  @Get('create')
  async create(@Query() args: Record<string, any>) {
    const { planId } = args;
    // 1.获取方案plan中的参数
    const plan = await this.planService.findOne(+planId);
    const { ziDaoxianNum, xiangNum, calcBets } = plan!;
    // 2.获取展示区段
    const showBets = [] as showBet[];
    for (let y = 0; y < xiangNum; y++) {
      for (let x = 0; x < ziDaoxianNum; x++) {
        const lst = calcBets.map((item) => {
          return {
            calcBetId: item.id,
            ziDaoxian: x + 1,
            xiang: y + 1,
          };
        });
        showBets.push(...(lst as showBet[]));
      }
    }
    // 3.创建多个展示区段
    await this.showBetService.createMany(showBets);
    return '创建成功';
  }

  @Post()
  async calculate(@Body() args: Record<string, any>) {
    // 1.获取showBets,在plan中有planId,
    const { planId, selectWires } = args;
    const showBets = await this.showBetService.createBets({ planId });
    let wireIndex = 0;
    showBets.map(async (item) => {
      // 2.展放导线
      // 如果导线的长度wireLong大于showBet的计算长度,那么表示导线就展放在当前的showBet
      if (selectWires[wireIndex].remain > item.calcBet.line) {
        selectWires[wireIndex].remain -= item.calcBet.line;
        this.wireService.update(selectWires[wireIndex].id, {
          showBets: {
            connect: { id: item.id },
          },
        });
      } else {
        selectWires[wireIndex].remain = 0;
        const chaShow = item.calcBet.line - selectWires[wireIndex].remain; // 计算还导线应该展放的长度
        this.wireService.update(selectWires[wireIndex].id, {
          showBets: {
            connect: { id: item.id },
          },
        });

        wireIndex++;
        // selectWires可能数量不够，如果不够，抛出异常
        if (!selectWires[wireIndex]) {
          throw new Error('导线数量不足');
        }
        selectWires[wireIndex].remain -= chaShow;
        this.wireService.update(selectWires[wireIndex].id, {
          showBets: {
            connect: { id: item.id },
          },
        });
      }
    });
  }
}
